package edu.yuhf.dbutil;

import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.yuhf.jdbcpart.UserTableOperation;

public class JdbcTemplate {
	public static int update(String sql,Object...param) {
		int rowNum=0;
		Connection conn=DBConnection.getConnection();
		try {
			PreparedStatement psmt=conn.prepareStatement(sql);
			ParameterMetaData pmd=psmt.getParameterMetaData();
			if(null!=param&&param.length!=0&&pmd.getParameterCount()==param.length) {
				for(int i=1;i<=param.length;i++) {
					psmt.setObject(i, param[i-1]);
				}
			}
			
			rowNum=psmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println(UserTableOperation.class.getName()+": update users by sql method error,message is "+e.getMessage());
		}finally {
			DBConnection.closeConnection(conn);
		}
		
		return rowNum;
		
	}
	public static <T> T query(String sql,ResultSetHandler<T> rsh,Object...param) {
		T t=null;
		Connection conn=DBConnection.getConnection();
		try {
			PreparedStatement psmt=conn.prepareStatement(sql);
			ParameterMetaData pmd=psmt.getParameterMetaData();
			if(null!=param&&param.length!=0&&pmd.getParameterCount()==param.length) {
				for(int i=0,len=param.length;i<len;i++) {
					psmt.setObject(i+1, param[i]);
				}
			}
			ResultSet rs=psmt.executeQuery();
			t=rsh.handler(rs);
		} catch (SQLException e) {
			System.out.println("update operation error,message is "+e.getMessage());
		}finally {
			DBConnection.closeConnection(conn);
		}
		return t;
	}
}
